class FairCalculator:
    def __init__(self, weighting_amount):
        self.weighting_amount = weighting_amount
        self._result = None

    def calcualte(self, book):
        bid = self._cal_side(book, 'bid')
        ask = self._cal_side(book, 'ask')
        if bid is None or ask is None:  # book厚度不足，无法计算fair
            result = None
        else:
            result = (bid + ask) / 2
        self._result = result
        return result

    def get(self):  # 读取上次计算结果
        return self._result

    def _cal_side(self, book, side):
        amt = self.weighting_amount
        price_sum = 0
        weight_sum = 0

        for p, v in book.items(side):
            if weight_sum + v < amt:
                price_sum += p * v
                weight_sum += v
            else:
                v = amt - weight_sum
                price_sum += p * v
                weight_sum += v
                return price_sum / weight_sum  # 计算加权平均

        return None  # 遍历book仍未达到足够权重
